package order

import (
	"context"
	"fmt"
	"sort"
	"strconv"

	"laundry-service/app/client/internal/svc"
	"laundry-service/app/client/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetOrderLogsLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetOrderLogsLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderLogsLogic {
	return &GetOrderLogsLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetOrderLogsLogic) GetOrderLogs(req *types.GetOrderLogsReq) (resp *types.GetOrderLogsResp, err error) {
	order, err := l.svcCtx.Db.FindOrderById(int(req.OrderId))
	if err != nil {
		return nil, err
	}

	resp = &types.GetOrderLogsResp{}
	resp.OrderId = uint(order.ID)
	resp.Number = order.Number

	slice := make([]*types.OrderLogItem, 0)

	orderLog, err := l.svcCtx.Db.GetOrderLogByOrderId(req.OrderId)
	if err != nil {
		return nil, err
	}

	preTitle := ""

	for _, v := range orderLog {
		if preTitle != v.Remark {
			slice = append(slice, &types.OrderLogItem{
				Title:     v.Remark,
				Desc:      "",
				Attr:      v.Attr,
				CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
			})
			preTitle = v.Remark
		}
	}

	expressLog, err := l.svcCtx.Db.GetExpressLogByOrderId(req.OrderId)
	if err != nil {
		return nil, err
	}

	preTitle = ""

	for _, v := range expressLog {
		if preTitle != v.OrderStateDesc {
			slice = append(slice, &types.OrderLogItem{
				Title:     v.OrderStateDesc,
				Desc:      "",
				Attr:      fmt.Sprintf("状态码：%s; 快递单号：%s; 快递员电话： %s", v.OrderStateCode, v.WaybillNo, v.EmpPhone),
				CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
			})
			preTitle = v.OrderStateDesc
		}
	}

	bagLog, err := l.svcCtx.Db.GetBagLogListByOrderId(int(req.OrderId))
	if err != nil {
		return nil, err
	}

	preTitle = ""

	for _, v := range bagLog {
		if preTitle != v.Remark {
			slice = append(slice, &types.OrderLogItem{
				Title:     v.Remark,
				Desc:      "",
				Attr:      fmt.Sprintf("状态码：%s", strconv.Itoa(v.State)),
				CreatedAt: v.CreatedAt.Format("2006-01-02 15:04:05"),
			})
			preTitle = v.Remark
		}
	}

	sort.Slice(slice, func(i, j int) bool {
		return slice[i].CreatedAt < slice[j].CreatedAt
	})

	resp.List = slice

	return resp, nil
}
